﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace OmniKits.Windows.Design
{
    public static class DesignLayoutUtility
    {
        public static void Move(this FrameworkElement target, Point offset)
        {
            if (target == null) return;

            var x = offset.X;
            var y = offset.Y;
            if (x == 0 && y == 0) return;

            var margin = target.Margin;

            if (x != 0)
            {
                var left = Canvas.GetLeft(target);
                if (!double.IsNaN(left))
                {
                    left += x;
                    Canvas.SetLeft(target, left);
                }
                var right = Canvas.GetRight(target);
                if (!double.IsNaN(right))
                {
                    right -= x;
                    Canvas.SetRight(target, right);
                }

                if (double.IsNaN(left) && double.IsNaN(right))
                {
                    switch (target.HorizontalAlignment)
                    {
                        case HorizontalAlignment.Left:
                            margin.Left += x;
                            break;
                        case HorizontalAlignment.Right:
                            margin.Right -= x;
                            break;
                        default:
                            margin.Left += x;
                            margin.Right -= x;
                            break;
                    }
                }
            }

            if (y != 0)
            {
                var top = Canvas.GetTop(target);
                if (!double.IsNaN(top))
                {
                    top += y;
                    Canvas.SetTop(target, top);
                }
                var bottom = Canvas.GetBottom(target);
                if (!double.IsNaN(bottom))
                {
                    bottom -= y;
                    Canvas.SetBottom(target, bottom);
                }

                if (double.IsNaN(top) && double.IsNaN(bottom))
                {
                    switch (target.VerticalAlignment)
                    {
                        case VerticalAlignment.Top:
                            margin.Top += y;
                            break;
                        case VerticalAlignment.Bottom:
                            margin.Bottom -= y;
                            break;
                        default:
                            margin.Top += y;
                            margin.Bottom -= y;
                            break;
                    }
                }
            }

            target.Margin = margin;
        }
    }
}
